﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Net;

namespace EbayScraper
{
    public partial class Form1 : Form
    {
        int ToProcess = 0;
        int Processed = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Ebay Scraper";
            ProcessButton.Enabled = false;
        }

        private void InputFileButton_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                ToProcess = File.ReadLines(openFileDialog1.FileName).Count();
                Processed = 0;
                ToProcNum.Text = ToProcess.ToString();
                ProcessButton.Text = "Process File";
                InputLabel.Text = "INPUT     FILE: " + openFileDialog1.SafeFileName;
                ProcessButton.Enabled = true;
                this.AcceptButton = ProcessButton;
                ProcessButton.Focus();
            }
        }

        private string readPage(string url)
        {
            HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
            webRequest.Method = @"GET";
            webRequest.Accept = @"image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, application/x-silverlight-2-b2, application/x-shockwave-flash, */*";
            webRequest.ContentType = @"application/x-www-form-urlencoded";
            webRequest.UserAgent = @"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SearchToolbar 1.2; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            Encoding enc = Encoding.GetEncoding("utf-8");
            // Read content    
            StreamReader loResponseStream = new StreamReader(webResponse.GetResponseStream(), enc);
            string lcHtml = loResponseStream.ReadToEnd();
            webResponse.Close();
            loResponseStream.Close();
            webRequest.GetResponse().Close();
            return lcHtml;
        }

        private string gTxtBtwn(string parse, string start, string fin)
        {
            //gets the text between these two strings;
            int i = (parse.IndexOf(start)==-1)?parse.Length:parse.IndexOf(start) + start.Length;
            string ret = parse.Substring(i);
            i = (ret.IndexOf(fin)==-1)?0:ret.IndexOf(fin);
            ret = (ret.Substring(0,i).Equals(""))?"N/A":ret.Substring(0, i);
            return ret;
        }

        private string GetInfo(string asin)
        {
            //rewrite to use ebay
            try
            {
                string url = @"http://www.ebay.com/itm/" + asin;
                string[] res = { "", "", "" };
                string page = readPage(url);
                //the above gets the page's source
                //so the below handles it
                /*looking for:
                 * auctiontitle:
                 * <h1 class="it-ttl" itemprop="name" id="itemTitle">
                 * <span class="g-hdn">Details about  &nbsp;</span>
                 * Datsun 240z,260z,280z Manual  Trans Flyweel Bolts - NOS
                 * </h1>
                 */
                res[0] = WebUtility.HtmlDecode( gTxtBtwn(page, "<span class=\"g-hdn\">Details about  &nbsp;</span>", "</h1>"));
                /* price:
                * <span class="notranslate" id="prcIsum" itemprop="price" style="">US $51.99</span>
                */
                res[1] = gTxtBtwn(page, ">US $", "</span>");
                /* mfptnum:
                * <td class="attrLabels">Manufacturer Part Number: </td>
                * <td width="50.0%"><h2 itemprop="mpn">700146</h2></td>
                * 
                */
                res[2] = gTxtBtwn(page, "<h2 itemprop=\"mpn\">", "</h2>");
                return csvValues(res);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), ex.GetType().ToString());
                return "";
            }
        }

        private string csvValues(string[] ary)
        {
            string retrn = "";
            foreach (string d in ary)
            {
                retrn += d + ",";
            }
            return retrn;
        }

        private void ProcessButton_Click(object sender, EventArgs e)
        {
            ProcessButton.Text = "Processing...";
            ProcessButton.Enabled = false;

            Cursor.Current = Cursors.WaitCursor;
            string PathOnly = Path.GetDirectoryName(openFileDialog1.FileName);
            string ShippingWeightInfoDataFile = @"EbayScrapeResult.csv";
            string line;
            string asin;
            string OutputData = "";
            string AuctionData = "";
            OutputLabel.Text = "OUTPUT FILE: " + ShippingWeightInfoDataFile;
            OutputLabel.Visible = true;
            OutputLabel.Refresh();
            using (StreamReader file = new StreamReader(openFileDialog1.FileName))
            {
                while ((line = file.ReadLine()) != null && Processed < ToProcess)
                {
                    asin = line.Replace(",", "");
                    AuctionData = GetInfo(asin);
                    OutputData += (AuctionData.Equals("")) ? "" : AuctionData + System.Environment.NewLine;
                    Processed++;
                    ToProcNum.Text = (ToProcess - Processed).ToString();
                    ProcNum.Text = Processed.ToString() + "";
                }
                file.Close();
            }
            System.IO.File.WriteAllText(ShippingWeightInfoDataFile, OutputData);
            Cursor.Current = Cursors.Default;
            ProcessButton.Text = "Complete";
        }



    }
}
